package com.scen.upload.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.scen.upload.common.Constants;
import com.scen.upload.domain.System;
import com.scen.upload.service.SystemService;
import com.scen.upload.utils.SelectView;
import com.scen.upload.vo.AjaxResult;
import com.scen.upload.vo.OtherNode;
import com.scen.upload.vo.OtherNodeBuilder;
import com.scen.upload.vo.SystemVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("system/other")
public class SystemController {

    @Autowired
    private SystemService systemService;

    /**
     * 查询省份城市层次json数据
     *
     * @param systemVo
     * @return
     */
    @ResponseBody
    @GetMapping("queryAddressNode")
    public SelectView queryAddressNode(SystemVo systemVo) {
        QueryWrapper<System> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(System.COL_STATUS, Constants.SYSTEM_STATUS1);
        List<System> list = this.systemService.list(queryWrapper);
        ArrayList<OtherNode> addressNodes = new ArrayList<>();
        for (System address : list) {
            Integer value = address.getId();
            Integer type = address.getType();
            String label = address.getDeployment();
            addressNodes.add(new OtherNode(value, type, label));
        }
        List<OtherNode> nodeList = OtherNodeBuilder.build(addressNodes, 3);
        return new SelectView(nodeList);
    }


    /**
     * 文件上传接口
     *
     * @param request
     * @param file
     * @return
     */
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    private Logger log = LoggerFactory.getLogger("SystemController");
    private String filePath = "E:/upload/";

    @PostMapping("uploadFile")
    public AjaxResult fileUploads(@RequestParam("file") MultipartFile file) throws Exception {
        // 得到格式化后的日期
        String format = sdf.format(new Date());
        // 获取上传的文件名称
        String fileName = file.getOriginalFilename();
        // 时间 和 日期拼接
        String newFileName = format + "_" + fileName;
        // 得到文件保存的位置以及新文件名
        File dest = new File(filePath + newFileName);
        try {
            // 上传的文件被保存了
            file.transferTo(dest);
            // 打印日志
            log.info("上传成功，当前上传的文件保存在 {}", filePath + newFileName);
            // 自定义返回的统一的 JSON 格式的数据，可以直接返回这个字符串也是可以的。
            return AjaxResult.success("上传成功");
        } catch (IOException e) {
            log.error(e.toString());
        }
        // 待完成 —— 文件类型校验工作
        return AjaxResult.fail("上传错误");
    }
}
